import {Component, OnInit} from '@angular/core';
import Common from '../../common/common';
import 'rxjs/add/operator/map';

import {ExtendHttpService} from "../../common/extend-http.service";
import {TipService} from "../../main/services/tip.service";
import {Router} from '@angular/router';
import {IndexService} from "../../main/services/index.service";
@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {


  // 密码登录和动态码登录切换
  isMobileLogin: boolean = true;

  // 加载组件状态
  isLoading: boolean = false;

  // 提示信息组件状态
  isShow = false;

  // 提示信息文字
  tipMsg = '';

  // 手机号密码对象
  mobilePwd = {
    mobile: '',
    login_pwd: '',
    merchant_id: ''
  }

  bottomMarginTop:number = 0;

  // 手机号动态码对象

  constructor(
    private extendHttp: ExtendHttpService,
    private tipService: TipService,
    private _router: Router,
    private _indexServie: IndexService
  ) {
  }

  ngOnInit() {
    let w1 = 441;
    let w2 = $(document).height();
    this.bottomMarginTop = w2 - w1- 53;
    let first = null;
    cBack =()=> {
      if (!first) {
        first = new Date().getTime();
        setTimeout(()=> {
          first = null;
        }, 1000);

      } else {
        if (new Date().getTime() - first < 1000) {
          webview.close()
        }
      }
    }
  }

  // 密码，验证码登录方式切换
  changeLoginMode() {
    this.isMobileLogin = !this.isMobileLogin;
  }

  onSubmitPwd() {
    if (!this.mobilePwd.mobile.trim()) {
      this.tipService.change(true, '请输入手机号');
      return;
    }
    if (!Common.mobileReg(this.mobilePwd.mobile)) {
      this.tipService.change(true, '手机号格式不正确');
      return;
    }

    if (!this.mobilePwd.login_pwd.trim()) {
      this.tipService.change(true, '请输入密码');
      return;
    }

    // 密码md5加密
    let params2 = Object.assign({}, this.mobilePwd);
    params2.login_pwd = hex_md5(params2.login_pwd);

    this.isLoading = !this.isLoading;
    this.loginFun(params2);
  }


  loginFun(params2) {
    this.extendHttp.post('/merchantApp/login', params2).subscribe(response => {
      let res = response.json();
      if (res['code'] === '0') {
        setTimeout(()=>{
          this.isLoading = !this.isLoading;
          localStorage.setItem('loginInfo',JSON.stringify(res));
          this._router.navigateByUrl('/main?loginFlag=true');
        }, 1000);
      } else if (res['code'] === '1') {
        this.isLoading = !this.isLoading;
        let paramsStr = JSON.stringify(res['merchantArr']);
        this._router.navigate(['/choose-shop'], {queryParams: {merchantArr: paramsStr, mobile: params2.mobile, login_pwd: params2.login_pwd}});
      } else {
        this.tipService.change(true, res['message']);
        this.isLoading = !this.isLoading;
      }
    }, error => {
      this.tipService.change(true, '系统繁忙，操作失败！');
      this.isLoading = !this.isLoading;
    });
  }
}
